package toy.keli.edic.util.media

import android.app.Activity
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.hardware.Camera
import android.provider.MediaStore
import android.widget.Toast
import androidx.core.app.ActivityCompat.startActivityForResult
import com.google.mlkit.vision.common.InputImage
import toy.keli.edic.util.ActivityRun
import toy.keli.edic.util.PermissionUtil
import android.view.Surface
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatActivity.RESULT_CANCELED
import androidx.compose.ui.graphics.asImageBitmap
import toy.keli.edic.CustomCameraActivity
import toy.keli.edic.CustomCameraActivity.Companion.EXTRA_PHOTO_PATH

class Camera {
    companion object {

        val ct = ActivityRun.context
        const val REQUEST_IMAGE_CAPTURE = 1
        fun getPhoto0(function: (texts: InputImage) -> Unit) {
            //权限
            if(!PermissionUtil.getPermission(ct, arrayOf("android.permission.CAMERA")){
                    getPhoto(function);
                }) return
            val takePictureIntent:Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply {  resolveActivity(ct.packageManager) }
            ActivityRun.onActivityResult {
                val resultCode = it.resultCode
                if (resultCode == RESULT_OK) {
                    val imageBitmap = it.data?.extras?.get("data") as Bitmap
                    var image = InputImage.fromBitmap(imageBitmap,0)
                    function(image)
                }
            }
            startActivityForResult(ct as Activity,takePictureIntent, REQUEST_IMAGE_CAPTURE,null)

        }

        // 修正后的获取图片方法
        fun getPhoto(function: (texts: InputImage) -> Unit) {
            // 检查相机权限
            if (!PermissionUtil.getPermission(ct, arrayOf(android.Manifest.permission.CAMERA)) {
                    getPhoto(function)
                }) return


            // 创建相机意图
            val takePictureIntent = Intent(ct, CustomCameraActivity::class.java)
            // 1. 注册结果回调（在初始化时，如 onCreate 中）
            val takePictureLauncher =  ActivityRun.onActivityResult { result ->
                if (result.resultCode == Activity.RESULT_OK) {
                    val data = result.data
                    // 处理返回的图片
                    val file = data?.extras?.getString(EXTRA_PHOTO_PATH);
                    val imageBitmap = BitmapFactory.decodeFile(file)
                    if (imageBitmap != null) {
//                        val rotationDegrees = getScreenRotationDegrees()
//                        val image = InputImage.fromBitmap(imageBitmap, rotationDegrees)
                        val image = InputImage.fromBitmap(imageBitmap,0);
                        function(image)
                    }
                }
            }
            takePictureLauncher.launch(takePictureIntent) // 使用 launcher 启动，而非 startActivityForResult

            //            val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply {
    //                resolveActivity(ct.packageManager) ?: run {
    //                    Toast.makeText(ct, "未找到相机应用", Toast.LENGTH_SHORT).show()
    //                    return
    //                }
    //            }

                // 注册 Activity 结果回调（推荐使用 Activity Result API 替代旧版方法）
//                ActivityRun.onActivityResult {result->
//                    val resultCode = result.resultCode
//                    if (resultCode == Activity.RESULT_OK) {
//                        val imageBitmap = result.data?.extras?.get("data") as Bitmap
//                        // 关键：计算图片需要的旋转角度
//                        val rotationDegrees = getScreenRotationDegrees()
//                        // 创建 InputImage 时传入正确的旋转角度
//                        val image = InputImage.fromBitmap(imageBitmap, rotationDegrees)
//                        function(image)
//                    }
//                }
//                startActivityForResult(ct as Activity,takePictureIntent, REQUEST_IMAGE_CAPTURE,null)
        }

        // 获取屏幕旋转对应的角度（核心方法）
        private fun getScreenRotationDegrees(): Int {
            val activity = ct as Activity;
            return when (activity.windowManager.defaultDisplay.rotation) {
                Surface.ROTATION_0 -> 0    // 屏幕正常方向
                Surface.ROTATION_90 -> 90  // 屏幕顺时针旋转90度
                Surface.ROTATION_180 -> 180 // 屏幕旋转180度
                Surface.ROTATION_270 -> 270 // 屏幕顺时针旋转270度
                else -> 0
            }
        }
    }
}